<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="100">
      </el-table-column>
      <el-table-column prop="saleprice" label="成本价" width="80">
      </el-table-column>
      <el-table-column prop="costprice" label="销售价" width="80">
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="80">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <!-- 自定义模板：通过scope可以获取到当前行对象：scope.row -->
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">上架</span>
          <span style="color: red" v-else-if="scope.row.state==0">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="150" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="150" sortable>
      </el-table-column>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"  :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice" >
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="saleprice" >
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="resources" label="图片上传">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="销售数量" prop="salecount" >
          <el-input v-model="saveForm.salecount" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="intro" >
          <quill-editor v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import Login from "../Login";
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      //显示图片的集合数据
      fileList:[],
      //显示店铺信息
      shop:[],
      //查询所有数上级部门
      petTree:[],

      /*列表数据*/
      pets: [],
      /*加载框  默认不显示*/
      listLoading: false,

      //分页的数据
      //总条数
      totals: 0,
      //每页显示的条数

      pageSize: 5,
      //当前第几页
      currentPage:1,

      //高级查询关键字
      keyword:'',
      //列表选中列
      sels: [],
      //编辑界面是否显示
      title:'',
      saveFormVisible: false,//新增界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          { required: true, message: '名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '访问url路径', trigger: 'blur' }
        ],
      },
      //编辑界面数据
      saveForm: {
        id:null,
        name:"",
        costprice:null,
        saleprice:null,
        resources:null,
        salecount:null,
        state:null,
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      },
    }
  },
  //方法
  methods: {
    //获取部门列表
    getProducts() {
      //参数
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      //显示盲等框
      this.listLoading = true;

      this.$http.post("/product",para).then(res=>{
        //关闭盲等框
        this.listLoading = false;
        this.pets = res.data.data;
        this.totals =res.data.totals;
      }).catch(res=>{
        this.$message.error('系统繁忙,请稍后再试!!!')
      });
    },

    //点击切换上下页的效果
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProducts();
    },

    //关键字查询
    keywordQuery() {
      this.currentPage  = 1;
      this.getProducts();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
        //点击确定按钮
      }).then(() => {
        this.listLoading = true;
        //请求异步请求
        this.$http.delete("/product/"+row.id).then(res =>{
          //关闭盲等框
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("删除成功");
            //当前页不是第一页       总条数-1   =      减去一页的页数 * 每页的数量
            if(this.currentPage!=1 && (this.totals-1)==(this.currentPage-1)*this.pageSize){
              this.currentPage=this.currentPage-1;
            }
            this.getProducts()
          }else {
            this.$message.error("网络繁忙,请稍后在式【500】")
          }
        }).catch(res =>{
          this.$message.error("网络繁忙,请稍后在式【404,400】")
        })
        //点击取消按钮
      }).catch(() => {

      });
    },

    //5.批量删除选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
        //点击确定按钮
      }).then(() => {
        this.listLoading = true;
        //发起请求
        this.$http.patch("/product",ids).then(res =>{
          //关闭盲等框
          this.listLoading = false;
          //删除成功后
          if(res.data.success){
            this.$message.success("操作成功");
            this.currentPage = 1;
            //从新获取数据
            this.getProducts();
          }else {
            //删除失败
            this.$message.success("网络繁忙,请稍后在式【500】")
          }
        }).catch(res =>{
          this.$message.error("网络繁忙,请稍后在式【404,400】")
        })
        //点击取消按钮
      }).catch(() => {
      });
    },

    //显示新增对话框
    handleAdd: function () {
      this.saveForm = {
        id:null,
        name:"",
        costprice:null,
        saleprice:null,
        resources:null,
        salecount:null,
        state:null,
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      };
      this.fileList = [];
      this.title = "新增";
      this.saveFormVisible = true;
    },

    /*点击修改弹出对话框*/
    handleEdit: function (index, row) {
      //回显数据：避免以前的数据发生改变
      this.saveForm = Object.assign({}, row);
      //显示对话框
      this.title = "修改";
      //清空图片,重新赋值
      this.fileList=[];
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",");
        for(var i=0;i<arr.length;i++){
          var item  = arr[i]
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
      this.saveFormVisible = true;
    },

    //新增或修改
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);
            let arr = para.typeId;
            if(arr && arr.length==0){
              para.typeId = null;
            }
            if(arr && arr.length>0){ //[1,13]
              para.typeId = arr[arr.length-1];
            }
            this.$http.put("/product",para).then(res=>{
              this.saveLoading = false;
              this.saveFormVisible = false;
              if(res.data.success){
                this.$message.success("操作成功");
                this.getProducts();
              }else {
                this.$message.error("网络繁忙【500】")
              }
            }).catch(res=>{
              this.$message.error("网络繁忙,请稍后在式【404,400】")
            })
          });
        }
      });
    },


    //上传成功后的触发
    handleSuccess(response, file, fileList){
      //对resources的处理 -增添到数据库
      if(this.saveForm.resources){
        this.saveForm.resources = this.saveForm.resources+","+response.resultObj;
      }else{
        this.saveForm.resources =response.resultObj;
      }
      //对象fileList的处理 --前端显示对象图片
      this.fileList=[];
      if(this.saveForm.resources){
        var arr = this.saveForm.resources.split(",")
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          this.fileList.push({"url":"http://123.207.27.208"+item})
        }
      }
    },
    //点击删除时触发
    handleRemove(file, fileList) {
      var path = file.url.substring(file.url.indexOf("/group"));
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message({
            message: '删除成功!',
            type: 'success'
          });
        }else{
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }

        //2.对resources处理
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for(var i=0;i<arr.length;i++){
            var itme = arr[i];
            if(path==itme){
              arr.splice(i,1);
            }
          }
          this.saveForm.resources = arr.join(",");
        }
        //3.对fileList做处理
        this.fileList = [];//先清空，再添加最新的数据
        if(this.saveForm.resources){
          var arr = this.saveForm.resources.split(",");
          for (var i=0;i<arr.length;i++){
            var item = arr[i];
            this.fileList.push({"url" : this.imgPrefix+item});
          }
        }
      })
    },

    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '请勾选哦亲！',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/onsale',ids).then((res) => {
          this.listLoading = false;
          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getProducts();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '请勾选哦亲',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/product/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getProducts();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
        this.$message.error("系统繁忙")
      });
    }
  },
  mounted() {
    this.getProducts();
  }
}
</script>

<style scoped>

</style>
